package com.example.chat.api;

import com.example.chat.model.User;
import com.example.chat.model.UserMapper;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class UserAPI {

    @Resource
    UserMapper userMapper;

    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest req) {

        User user = userMapper.selectByName(username);

        if (user == null || !user.getPassword().equals(password)) {
            System.out.println("登陆失败！用户名或密码错误 " + user);
            return new User();
        }

        HttpSession session = req.getSession(true);
        session.setAttribute("user", user);

        user.setPassword("");

        return user;
    }

    @PostMapping("/register")
    @ResponseBody
    public Object register(String username, String password) {

        User user = null;

        try {
            user = new User();

            user.setUsername(username);
            user.setPassword(password);
            int ret = userMapper.insert(user);

            System.out.println("注册 ret：" + ret);

            user.setPassword("");
        } catch (DuplicateKeyException e) {
            user = new User();
            System.out.println("注册失败！ username = " + username);
        }

        return user;
    }

    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest req) {

        HttpSession session = req.getSession(false);
        if (session == null) {
            System.out.println("[getUserInfo] 当前请求中获取不到 session对象！");

            return new User();
        }

        User user = (User) session.getAttribute("user");
        if (user == null) {
            System.out.println("[getUserInfo] 当前会话中获取不到 user对象");
            return new User();
        }

        user.setPassword("");

        return user;
    }
}